package org.example;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DQLTest {
    String driverClass = "com.mysql.cj.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/briup";
    String username = "root";
    String password = "root1234";
    @Test
    public void selectTable() {
        Connection conn = null;
        Statement stmt = null;
        try {
//            1. 注册驱动
            Class.forName(driverClass);
//        2. 获取数据库连接对象
            conn = DriverManager.getConnection(url,username, password);
//        3. 获取数据库操作对象（ Statement 类型或者子类型对象）
            stmt = conn.createStatement();
//        4. 执行sql语句
            String sql = "select * from mytable";
            ResultSet rs = stmt.executeQuery(sql);
//        5. 处理结果集（如果需要的话，一般查询语句必须要处理）
            while (rs.next()){
                System.out.println(rs.getInt("id") + " " + rs.getInt("age") + " " + rs.getString("gender"));
            }
            System.out.println(rs);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}
